import re
import numpy as np
import pandas as pd
from pathlib import Path
from typing import Dict, List

def extract_single_model_metrics(model_name: str, runs: int = 3) -> Dict:
    """提取单个模型的所有轮次实验指标"""
    model_root = Path(f"../results_{model_name}")  # 相对于analysis目录的路径
    if not model_root.exists():
        raise FileNotFoundError(f"模型结果文件夹不存在: {model_root}")

    # 匹配日志中的关键指标（根据实际日志格式调整正则）
    acc_pattern = re.compile(r"最佳验证准确率: (\d+\.\d+)")  # 中文日志匹配
    train_loss_pattern = re.compile(r"训练损失: (\d+\.\d+)")
    val_accs: List[float] = []
    final_train_losses: List[float] = []

    for run_id in range(runs):
        run_dir = model_root / f"run_{run_id}"
        log_files = list(run_dir.glob("日志/*.log"))  # 日志目录为中文
        if not log_files:
            raise FileNotFoundError(f"未找到轮次 {run_id} 的日志文件: {run_dir}")
        log_file = log_files[0]

        # 读取日志内容
        with open(log_file, "r", encoding="utf-8") as f:
            log_content = f.read()

        # 提取最佳验证准确率
        acc_match = acc_pattern.search(log_content)
        if acc_match:
            val_accs.append(float(acc_match.group(1)))
        else:
            raise ValueError(f"轮次 {run_id} 日志中未找到最佳验证准确率")

        # 提取最后一轮训练损失（可选）
        loss_lines = re.findall(train_loss_pattern, log_content)
        if loss_lines:
            final_train_losses.append(float(loss_lines[-1]))  # 取最后一轮损失

    return {
        "模型名称": model_name.replace("_", " "),
        "轮次准确率": val_accs,
        "均值准确率": np.mean(val_accs).round(4),
        "标准差": np.std(val_accs).round(4),
        "最终训练损失": [round(loss, 4) for loss in final_train_losses] if final_train_losses else None
    }

def extract_all_models(runs: int = 3) -> pd.DataFrame:
    """提取所有模型的指标并整理为DataFrame"""
    models = ["simple_cnn", "lenet5", "multi_scale_cnn"]
    all_results = []
    for model in models:
        metrics = extract_single_model_metrics(model, runs)
        all_results.append(metrics)
    return pd.DataFrame(all_results)

if __name__ == "__main__":
    # 提取3轮实验结果并保存为CSV
    results_df = extract_all_models(runs=3)
    results_df.to_csv("../experiment_metrics.csv", index=False, encoding="utf-8-sig")
    print("指标提取完成，保存至 experiment_metrics.csv")
    print("\n提取结果预览：")
    print(results_df)